package my.diplom.dao.impl;

import my.diplom.dao.IProjectDAO;
import my.diplom.entity.Project;
import my.diplom.entity.User;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;

/**
 * Created by IntelliJ IDEA.
 * User: gb
 * Date: 14.07.2009
 * Time: 16:14:09
 * To change this template use File | Settings | File Templates.
 */
public class ProjectDAOImpl implements IProjectDAO {

    private static final Logger log = Logger.getLogger(ProjectDAOImpl.class);

    private HibernateTemplate template;

    public void setTemplate(HibernateTemplate template) {
        this.template = template;
    }


    public void create(Project project) {
        log.debug("create project " + project.getProjectName());
        template.save(project);
    }

    public void update(Project project) {
        log.debug("update project " + project.getProjectName());
        template.saveOrUpdate(project);
    }

    public Project getById(Long projectId) {
        log.debug("get project by id = " + projectId);
        return (Project) template.get(Project.class, projectId);
    }

    public Project getById(Long projectId, boolean initUsers) {
        log.debug("get project by id = " + projectId);
        Project project = (Project) template.get(Project.class, projectId);
        if (initUsers) {
            template.initialize(project.getUsers());
        }
        return project;
    }


    public List<Project> getAll() {
        log.debug("get all projects");
        //noinspection JpaQlInspection
        return template.find("from Project order by projectName");
    }

    public Project getByName(String projectName) {
        log.debug("get project by name = " + projectName);
        //noinspection JpaQlInspection
        return (Project) (template.find("from Project p where p.projectName = ?", projectName).get(0));
    }

    public void delete(Project project) {
        log.debug("delete project " + project.getProjectName());
        template.delete(project);
    }

    @Override
    public List<Project> getByUser(User user) {
        log.debug("get project by user = " + user.getLogin());
        return template.find("select p from Project p, User u where u in elements (p.users) and u=? ", user);
    }


    @Override
    public List<Project> getByLogin(String login) {
        log.debug("get project by user = " + login);
        return template.find("select p from Project p, User u where u in elements (p.users) and u.login = ?", login);
    }
}
